package com.jifen.utils;
/**
 * 类名：WxPaySignatureUtils
 * 版本：1.0.0
 * 作者: zhang
 * 日期: 2019/6/6 11:20
 * 说明: 微信支付加密工具类
 */
import java.security.MessageDigest;
import java.util.*;

public class WxPaySignatureUtils {

    /**
     * 微信支付加密工具
     * MD5
     */
    public static String signature(SortedMap<String, Object> map, String key) {
        Set<String> keySet = map.keySet();
        String[] str = new String[map.size()];
        StringBuilder tmp = new StringBuilder();
        // 进行字典排序
        str = keySet.toArray(str);
        Arrays.sort(str);
        for (int i = 0; i < str.length; i++) {
            String t = str[i] + "=" + map.get(str[i]) + "&";
            tmp.append(t);
        }
        if (null != key) {
            tmp.append("key=" + key);
        }
        return md5(tmp.toString().getBytes()).toUpperCase();
    }

    /**
     * 微信支付加密工具
     * SHA
     */
    public static String signatureSHA1(SortedMap<String, Object> map) {
        Set<String> keySet = map.keySet();
        String[] str = new String[map.size()];
        StringBuilder tmp = new StringBuilder();
        // 进行字典排序
        str = keySet.toArray(str);
        Arrays.sort(str);
        for (int i = 0; i < str.length; i++) {
            String t = str[i] + "=" + map.get(str[i]) + "&";
            tmp.append(t);
        }

        String tosend = tmp.toString().substring(0, tmp.length() - 1);
        System.out.println("tosend:"+tosend);
        MessageDigest md = null;
        byte[] bytes = null;
        try {

            md = MessageDigest.getInstance("SHA-1");
            bytes = md.digest(tosend.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        String singe = byteToStr(bytes);
        return singe.toLowerCase();

    }

    public static String sha1Check(String[] str) {
        StringBuilder tmp = new StringBuilder();
        Arrays.sort(str);
        for (int i = 0; i < str.length; i++) {
            String t = str[i];
            tmp.append(t);
        }
        String tosend = tmp.toString();
        MessageDigest md = null;
        byte[] bytes = null;
        try {
            md = MessageDigest.getInstance("SHA-1");
            bytes = md.digest(tosend.getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        String singe = byteToStr(bytes);
        return singe.toUpperCase();
    }

    /**
     * 字节数组转换为字符串
     *
     * @param byteArray
     * @return
     */
    public static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 字节转换为字符串
     *
     * @param mByte
     * @return
     */
    public static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        String s = new String(tempArr);
        return s;
    }

    /**
     * 验证签名
     * @param smap
     * @param key
     * @return
     */
    public static boolean validateSign(SortedMap<String, Object> smap, String key) {
        StringBuffer sb = new StringBuffer();
        Set es = smap.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            if (!"sign".equals(k) && null != v && !"".equals(v) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + key);
        /** 验证的签名 */
        String sign = md5(sb.toString().getBytes()).toUpperCase();
        /** 微信端返回的合法签名 */
        String validSign = ((String) smap.get("sign")).toUpperCase();
        return validSign.equals(sign);
    }

    public final static String md5(byte[] buffer) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(buffer);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
}
